<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>WebJsBridge</title>
</head>

<body>
	<button class="hello-btn">hello</button>
	<button class="toast-btn">toast</button>
	<button class="confirm-btn">确认弹窗</button>
	<button class="show-loading-btn">显示Loading框</button>
	<button class="get-device-info-btn">获取设备信息</button>
	<button class="md5-btn">MD5加密</button>
	<button class="base64-btn">base64编解码</button>
	<button class="aes-btn">AES加解密</button>
	<button class="test-async-btn">测试异步任务</button>

	<!-- VConsole 调试工具 -->
	<script src="./lib/vconsole.min.js"></script>
	<!-- lodash库 -->
	<script src="./lib/lodash.min.js"></script>
	<!-- base64编解码 -->
	<script src="./lib/base64.js"></script>
	<!-- 加解密库 -->
	<script src="./lib/crypto.js"></script>
	<script src="./js/encryption.js"></script>
	<script>
		// 初始化VConsole
		var vConsole = new window.VConsole();

		var helloBtn = document.querySelector('.hello-btn');
		var toastBtn = document.querySelector('.toast-btn');
		var confirmBtn = document.querySelector('.confirm-btn');
		var showLoadingBtn = document.querySelector('.show-loading-btn');
		var getDeviceInfoBtn = document.querySelector('.get-device-info-btn');
		var md5Btn = document.querySelector('.md5-btn');
		var base64EncodeBtn = document.querySelector('.base64-btn');
		var aesBtn = document.querySelector('.aes-btn');
		var testAsyncBtn = document.querySelector('.test-async-btn');

		// 封装一个对象，统一封装原生Native端和Flutter端的JS交互
		var webJsBridge = {
			// 是否在Flutter环境
			isInFlutter: window.flutter_inappwebview !== undefined,
			// 是否在原生环境
			isInNative: window.WebViewJavascriptBridge !== undefined,
			// 是否在客户端环境
			isClientPlaform: this.isInFlutter || this.isInNative,
			// 初始化方法
			init: function () {
				if (this.isInFlutter) {
					// Flutter环境
					window.addEventListener("flutterInAppWebViewPlatformReady", function () {
						console.log("Flutter bridge => 初始化成功");
					});
				} else {
					// 普通安卓环境
					function connectWebViewJavascriptBridge(callback) {
						if (window.WebViewJavascriptBridge) {
							callback(WebViewJavascriptBridge)
						} else {
							document.addEventListener(
								'WebViewJavascriptBridgeReady',
								function () {
									console.log("bridge => 连接成功");
									callback(WebViewJavascriptBridge)
								},
								false
							);
						}
					}

					//注册回调函数，第一次连接时调用 开始初始化
					connectWebViewJavascriptBridge(function (bridge) {
						//初始化
						bridge.init(function (message, responseCallback) {
							console.log("bridge => 初始化成功");
							var data = {
								'Javascript Responds': 'Wee!'
							};
							responseCallback(data);
						});

						//Android调用js方法：functionInJs方法名称需要保持一致 ，并返回给Android通知
						bridge.registerHandler("functionInJs", function (data, responseCallback) {
							alert(data);
							var data2 = document.getElementById("text1").value;
							var responseData = "我是Android调用js方法返回的数据---" + data2;
							responseCallback(responseData);
						});
					});
				}
			},
			// 调用Native端或Flutter端的方法
			callHandler: function (handlerName, params, callback) {
				if (this.isInFlutter) {
					window.flutter_inappwebview
						.callHandler(handlerName, params)
						.then(function (result) {
							if (callback !== undefined) {
								callback(result);
							}
						});
				} else {
					window.WebViewJavascriptBridge.callHandler(handlerName, params, function (result) {
						if (callback !== undefined) {
							callback(result);
						}
					});
				}
			}
		};

		// 初始化
		webJsBridge.init();

		// ---------------------------------------------------

		function showAlertDialog(title, content) {
			webJsBridge.callHandler("showAlertDialog", {
				"title": title,
				"content": content,
				"confirmText": "确认",
				"cancelText": "取消"
			}, function (result) {
				console.log('调用结果：' + result);
			});
		}

		function showToast(msg) {
			var params = {
				"msg": msg
			};
			webJsBridge.callHandler("toast", params, function (result) {
				console.log('调用结果：' + result);
			});
		}

		// 防抖函数
		function debounce(callback, timeout) {
			timeout = timeout || 500;
			var useLodash = true;
			if (useLodash) {
				return _.debounce(callback, timeout);
			} else {
				return debounceWithMy(callback, timeout);
			}
		}

		// 自己实现的防抖函数
		function debounceWithMy(callback, timeout) {
			var tId;
			return function (...args) {
				// 每次都清除上一次的延时器
				clearTimeout(tId);
				// 开启延时器
				tId = setTimeout(() => {
					// 到时间，调用回调函数
					if (callback) {
						callback.apply(this, args);
					}
				}, timeout);
			};
		}

		// ---------------------------------------------------

		helloBtn.addEventListener('click', debounce(function (e) {
			webJsBridge.callHandler("hello", {
				text: ' 你好'
			}, function (result) {
				var text = JSON.parse(result).data.text;
				showToast(text);
			});
		}));

		// 调用Native端的toast方法
		toastBtn.addEventListener('click', debounce(function (e) {
			showToast("你好，我是来自Web端的文字");
		}));

		// 调用Native端的showAlertDialog方法
		confirmBtn.addEventListener('click', debounce(function (e) {
			showAlertDialog("我是标题", "我是内容");
		}));

		// 调用Native端的showWait方法
		showLoadingBtn.addEventListener('click', debounce(function (e) {
			webJsBridge.callHandler("showWait", {}, function (result) {
				console.log('显示Loading...');
				// 2秒后隐藏Loading弹窗
				setTimeout(() => {
					webJsBridge.callHandler("hideWait", {}, function (result) {
						console.log('隐藏Loading...');
					});
				}, 2000);
			});
		}));

		// 调用Native端的getDeviceInfo方法
		getDeviceInfoBtn.addEventListener('click', debounce(function (e) {
			webJsBridge.callHandler("getDeviceInfo", {}, function (result) {
				var resp = JSON.parse(result);
				var deviceInfo = resp.data;
				// deviceInfo.deviceAndroidVersionCode, 
				showAlertDialog(
					'设备的安卓版本：' + deviceInfo.deviceAndroidVersionName,
					'设备的唯一Id：' + deviceInfo.uniqueDeviceId
				);
			});
		}));

		// 调用Native端的md5方法
		md5Btn.addEventListener('click', debounce(function (e) {
			if (webJsBridge.isClientPlaform) {
				var params = {
					"text": "88888888"
				};
				webJsBridge.callHandler("md5", params, function (result) {
					var text = JSON.parse(result).data.text;
					showToast(text);
				});
			} else {
				alert(md5Encrypt('88888888'));
			}
		}));

		base64EncodeBtn.addEventListener('click', debounce(function () {
			var encodeResult = base64Encode('123456');
			var decodeResult = base64Decode(encodeResult);
			alert('编码结果：' + encodeResult);
			alert("解码结果：" + decodeResult)
		}));

		aesBtn.addEventListener('click', debounce(function (e) {
			var originalString = "Hello, world!";
			// 密钥
			var key = "my-secret-key";
			// 加密
			var encryptedString = aesEncrypt(originalString, key);
			// 解密
			var decryptedString = aesDecrypt(encryptedString, key);;
			console.log("原始字符串：", originalString);
			console.log("加密后：", encryptedString);
			console.log("解密后：", decryptedString);
		}));

		// 测试异步方法
		testAsyncBtn.addEventListener('click', debounce(function (e) {
			webJsBridge.callHandler("testAsync", {}, function (result) {
				showToast(result);
			});
		}));
	</script>
</body>

</html>